//
//  WBStatusViewModel.swift
//  CZweibo
//
//  Created by jyh on 2017/12/12.
//  Copyright © 2017年 jyh. All rights reserved.
//

import Foundation

// 单条微博视图模型
class WBStatusViewModel: CustomStringConvertible {

    // 遵守CustomStringConvertible,就会有description

    // 微博模型
    var status: WBStatus
    
    // 会员图标
    var mbrankIcon: UIImage?
    // vip图标
    var vipIcon: UIImage?
    // 转发文字
    var retweetedStr: String?
    // 评论文字
    var commentStr: String?
    // 点赞文字
    var likeStr: String?
    // 配图视图大小
    var pictureViewSize = CGSize()
    
    //<a href="http://app.weibo.com/t/feed/6vtZb0" rel="nofollow">微博 weibo.com</a>"
    /// 构造函数
    ///
    /// - Parameter model: 微博模型
    
    init(model: WBStatus) {
        self.status = model
        
        if model.user?.mbrank ?? 0 > 0 && model.user?.mbrank ?? 0 < 7 {
            
            mbrankIcon = UIImage(named: "common_icon_membership_level\(model.user?.mbrank ?? 1)")
        }
        
        switch model.user?.verified_type ?? -1 {
        case 0:
            vipIcon = #imageLiteral(resourceName: "avatar_vip")
        case 2,3,5:
            vipIcon = #imageLiteral(resourceName: "avatar_enterprise_vip")
        case 0:
            vipIcon = #imageLiteral(resourceName: "avatar_grassroot")
        default:
            break
        }
        
        // 设置底部计算字符串
        retweetedStr = countString(count: model.reposts_count, defaultStr: "转发")
        commentStr = countString(count: model.comments_count, defaultStr: "评论")
        likeStr = countString(count: model.attitudes_count, defaultStr: "赞")

        pictureViewSize = calcPictureViewSize(count: status.pic_urls?.count)
        
    }
    
    var description: String {
        
        return status.description
    }
    
    private func calcPictureViewSize(count: Int?) -> CGSize {
  
        if count == 0 || count == nil {
            return CGSize()
        }

        // 计算高度
        /*
         // 九宫格计算方式
         1 2 3 = 0 1 2 / 3 = 0 + 1 = 1
         4 5 6 = 3 4 5 / 3 = 1 + 1 = 2
         7 8 9 = 6 7 8 / 3 = 2 + 1 = 3
         */
        // 行
        let row = (count! - 1) / 3 + 1
        // 搞
        var height = WBStatusPictureViewOutterMargin
            height += CGFloat(row) * WBStatusPictureItemWidth
            height += CGFloat(row - 1) * WBStatusPictureViewInnerMargin
        
        return CGSize(width: WBStatusPictureViewWidth, height: height)
    }
    
    
    /// Description
    ///
    /// - Parameters:
    ///   - count: 数字
    ///   - defaultStr: 默认字符串
    /// - Returns: 结果
    private func countString(count: Int, defaultStr: String) -> String {
        
        if count == 0 {
            return defaultStr
        }
        
        if count < 10000 {
            return count.description
        }
        
        return String(format: "%.02f 万", Double(count) / 10000)
    }
}
